/*
 * @Author: wanli wanliofficial@aliyun.com
 * @Date: 2025-05-13 15:01:19
 * @LastEditors: wanli wanliofficial@aliyun.com
 * @LastEditTime: 2025-05-14 10:47:32
 * @FilePath: \locust4j-http-load\src\main\java\io\github\nejckorasa\locust4j\http\Main.java
 * @Description: 
 * 
 * Copyright (c) 2025 by wanli email: wanliofficial@aliyun.com, All Rights Reserved. 
 */
package io.github.nejckorasa.locust4j.http;

import java.util.Arrays;
import java.util.stream.Collectors;

import com.github.myzhan.locust4j.AbstractTask;
import com.github.myzhan.locust4j.Locust;

import io.github.nejckorasa.locust4j.http.generator.RandomGetGenerator;
import io.github.nejckorasa.locust4j.http.generator.RandomPostGenerator;
import io.github.nejckorasa.locust4j.http.config.ConfigurationContext;
import io.github.nejckorasa.locust4j.http.task.GetExampleTask;
import io.github.nejckorasa.locust4j.http.task.PostExampleTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Main {

	private static final Logger logger = LogManager.getLogger(Main.class);

	private Main() {
	}

	public static void main(final String[] args) {

		try {
			ConfigurationContext.init(args);

			// override options here - should remove this when executing jar

			ConfigurationContext.getConfiguration().setBaseUrl("http://192.168.1.149:8080/");
			ConfigurationContext.getConfiguration().setMasterPort(12345);
			ConfigurationContext.getConfiguration().setMasterHost("127.0.0.1");
			ConfigurationContext.getConfiguration().setDryRun(false);
		} catch (final Exception ex) {
			logger.error("Failed to initialize GlobalConfiguration, will exit now", ex);
		}

		final Locust locust = Locust.getInstance();
		locust.setMasterHost(ConfigurationContext.getConfiguration().getMasterHost());
		locust.setMasterPort(ConfigurationContext.getConfiguration().getMasterPort());

		// enable max RPS control
		if (ConfigurationContext.getConfiguration().getMaxRPS() > 0) {
			locust.setMaxRPS(ConfigurationContext.getConfiguration().getMaxRPS());
		}

		AbstractTask get0 = new GetExampleTask(30, "538743863");
		AbstractTask pet0 = new PostExampleTask(5, "427420394");
		AbstractTask pet1 = new PostExampleTask(5, "46324312");
		AbstractTask pet2 = new PostExampleTask(5, "538743855");

		// define tasks here
		final AbstractTask[] tasks = {
				get0,
				pet0,
				pet1,
				pet2
		};

		printTasks(tasks);

		if (ConfigurationContext.getConfiguration().isDryRun()) {
			logger.info("Dry running...");
			locust.dryRun(tasks);
		} else {
			locust.run(tasks);
		}
	}

	private static void printTasks(final AbstractTask[] tasks) {
		logger.info(
				"Running tasks \n" + Arrays.stream(tasks).map(t -> "(" + t.getWeight() + ", " + t.getName() + ") \n")
						.collect(Collectors.joining("[", ",", "]")));
	}
}
